import React, { useMemo } from 'react'
import { Descriptions as AntdDescriptions, Typography } from 'antd'
import { useT } from '@designable/event-system'
import { createSchemaField, useFieldSchema, useForm } from '@formily/react'
import { observer } from '@formily/reactive-react'
import { createEvent, CreateExecutor } from '@designable/event-system'
import DesensitizationBox from '../DesensitizationBox'

export interface DetailContainerProps {
  title?: string
  className?: string
  style?: React.CSSProperties
  buttons?: any[]
  value?: any
  bordered?: boolean
  column?: number | Partial<Record<string, number>>
  size?: 'default' | 'middle' | 'small'
  layout?: 'horizontal' | 'vertical'
  [key: string]: any
}

const Text: React.FC<{
  value?: string
  nameKey?: string
  children?: React.ReactNode
  onClickExpression?: string
  desensitize?: boolean
}> = observer((props) => {
  const form = useForm()
  const formValues = form.getFormState().values
  const { onClickExpression, desensitize, nameKey } = props

  // 根据 nameKey 获取对应的值
  const getValueByKey = (key?: string) => {
    if (!key) return props.value || props.children

    // 支持嵌套属性访问，如 'user.name'
    const keys = key.split('.')
    let value = formValues

    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k]
      } else {
        return props.value || props.children // 如果找不到，返回默认值
      }
    }

    return value
  }

  // 处理点击事件
  const handleClick = async () => {
    if (onClickExpression) {
      try {
        await createEvent(onClickExpression, {
          values: formValues,
          form,
        })
      } catch (error) {
        console.warn('点击事件表达式执行失败:', error)
      }
    }
  }

  const content = getValueByKey(nameKey)
  const contentElement = desensitize ? (
    <DesensitizationBox data={content} />
  ) : (
    content
  )

  if (onClickExpression) {
    return (
      <Typography.Link onClick={handleClick}>{contentElement}</Typography.Link>
    )
  } else {
    return <div style={{ color: '#777' }}>{contentElement}</div>
  }
})

export interface AntdDetailContainerWrapperProps {
  buttons?: any[]
  bordered?: boolean
  column?: number | Partial<Record<string, number>>
  size?: 'default' | 'middle' | 'small'
  layout?: 'horizontal' | 'vertical'
  children?: React.ReactNode
  [key: string]: any
}

export const AntdDetailContainerWrapper: React.FC<AntdDetailContainerWrapperProps> =
  observer(
    ({
      bordered = false,
      column = 3,
      size = 'default',
      layout = 'horizontal',
      children,
      ...props
    }) => {
      return (
        <AntdDescriptions
          bordered={bordered}
          column={column}
          size={size}
          layout={layout}
          {...props}
        >
          {children}
        </AntdDescriptions>
      )
    }
  )

export const DetailContainer: React.FC<DetailContainerProps> = observer(
  ({ className, style, ...props }) => {
    const $t = useT()
    const fieldSchemaProperties = useFieldSchema().properties || {}
    const form = useForm()
    const formValues = form.getFormState().values

    const items = (Object.values(fieldSchemaProperties) || [])
      .map((item) => {
        const schema = {
          ...item,
          type: 'void',
          'x-component': 'Text',
        }

        const componentProps = item['x-component-props'] || {}
        const visibleExpression = componentProps.visibleExpression
        if (visibleExpression) {
          try {
            componentProps.visible =
              CreateExecutor(visibleExpression)(formValues)
          } catch (error) {
            console.warn('表达式执行失败:', error)
            componentProps.visible = true // 默认显示
          }
        } else {
          componentProps.visible = true
        }

        return {
          ...componentProps,
          schema: {
            type: 'void',
            properties: {
              [item['x-designable-id']]: schema,
            },
          },
        }
      })
      .filter((item) => item.visible)

    const SchemaField = useMemo(() => {
      return createSchemaField({
        components: {
          Text,
        },
        scope: { $t },
      })
    }, [$t])

    return (
      <div className={className} style={style}>
        <AntdDetailContainerWrapper {...props}>
          {items.map((item, index) => (
            <AntdDescriptions.Item
              key={item.key || index}
              label={item.label}
              span={item.span}
            >
              {item.schema ? (
                <SchemaField schema={item.schema} />
              ) : (
                <Text value="后备文本" />
              )}
            </AntdDescriptions.Item>
          ))}
        </AntdDetailContainerWrapper>
      </div>
    )
  }
)
